import { useMemo, useState } from "react";
import { Form, Input, Button } from "antd-mobile";
import request from "../../api/request";
import { Checkbox, Toast, Modal } from "antd-mobile";
import ImageIcon from "../../../public/loginIcon03.jpg";
import { NavBar, Tabs } from "antd-mobile";
import { useNavigate } from "react-router-dom";
import style from "./index.module.css";
import axios from "axios";
import { useCountdown } from "../../utils/useCountdown";
import { useDebunce } from "../../utils/useDebunce";
import { setUserInfo, getUserRole } from "../../utils/permission";
function Index() {
  const navigate = useNavigate();
  const back = () => navigate(-1);
  const [agreed, setAgreed] = useState(false);

  const onFinish = async(values: any) => {
    if (!agreed) {
      Toast.show({ content: "请先勾选并同意相关协议" });
      return;
    }

    console.log(values);

    const res = await request.get('/api/login',{
      params:{
        phone:values.phone,
        code:values.code
      }
    })
    console.log('判断验证码是否正确',res);

    if(res.code === 20000){
      navigate("/index");
    }
    else{
      Toast.show({ content: res.msg });
    }
    // const res1 = await axios.post("/mock/login", {
    //   username: "admin",        // 可选值：admin, doctor, patient, test
    //   password: "123456"        // 对应密码：123456, doctor123, patient123, test123
    // });
    // console.log(res1)
    
    
      
    
    // 获取表单中的手机号
    const phone = form.getFieldValue("phone");
    const token = Math.round(Math.random() * 2000).toString();

    // 设置用户信息（包含角色）
    setUserInfo(phone || "unknown", token);

    const userRole = getUserRole();
    const roleText = userRole === "admin" ? "管理员" : "普通用户";

    Toast.show({ content: `登录成功，欢迎${roleText}！` });
    // navigate("/index");

    
  };

  
  

  const { count, CountDown } = useCountdown();
  const maxNum = 60;
  const [form] = Form.useForm();

  const sendCode = useMemo(() => {
    if (count === maxNum) return "获取验证码";
    return `${count}秒后重新获取`;
  }, [count]);

  const handBtn = useDebunce(() => {
    if (!agreed) {
      Modal.alert({
        content:
          "为了更好地保障您的合法权益，请您阅读并同意 《妙手医生服务协议》和《妙手医生隐私政策》、《妙手医生儿童个人信息保护规则》 ",
        confirmText: "确定",
        onConfirm: () => {
          console.log("确定");
          setAgreed(true);
        },
      });
      return;
    }

    form.validateFields().then(async ({ phone, code }) => {
      CountDown();
      const res = await request.post("/api/login", {
        phone: phone,
        code: code,
      });

     ;

      // admin 管理员 user 普通用户
      const userRole = phone === "18332266897" ? "admin" : "user";
      localStorage.setItem("userRole", userRole);
      localStorage.setItem("userPhone", phone);
      console.log(res);
      setInterval(() => {
        form.setFieldValue("code", res.data);
      }, 2000);
    });

    
  }, 1000);



  return (
    <div className={style.login}>
      <NavBar onBack={back}></NavBar>
      <img
        className={style.img}
        style={{ width: "180px", height: "70px" }}
        src={ImageIcon}
        alt=""
      />

      <Tabs>



        <Tabs.Tab title="手机号登录" key="phone">
          <Form
            form={form}
            name="form"
            onFinish={onFinish}
            footer={
              <Button
                className={style.btn}
                block
                type="submit"
                color="primary"
                size="large"
                disabled={!agreed}
              >
                登录
              </Button>
            }
          >
            <Form.Item
              name="phone"
              label="+86"
              className={style.inputPhone}
              rules={[{ required: true, message: "手机号不能为空" }]}
            >
              <Input
                style={{ marginLeft: "50px" }}
                placeholder="请输入手机号"
              />
            </Form.Item>

            <Form.Item
              name="code"
              extra={
                <Button
                  disabled={count !== maxNum}
                  onClick={() => handBtn()}
                  className={style.sendMsg}
                >
                  {sendCode}
                </Button>
              }
            >
              <Input placeholder="输入验证码" />
            </Form.Item>
          </Form>
        </Tabs.Tab>





        <Tabs.Tab title="密码登录" key="passwords">
          <Form
            name="form1"
            onFinish={onFinish}
            footer={
              <Button
                className={style.btn}
                block
                type="submit"
                color="primary"
                size="large"
                disabled={!agreed}
              >
                登录
              </Button>
            }
          >
            <Form.Item
              name="username"
              label="账号"
              className={style.inputPhone}
              rules={[{ required: true, message: "账号不能为空" }]}
            >
              <Input style={{ marginLeft: "50px" }} placeholder="请输入账号" />
            </Form.Item>

            <Form.Item
              name="password"
              label="密码"
              className={style.inputPhone}
              rules={[{ required: true, message: "密码不能为空" }]}
            >
              <Input style={{ marginLeft: "50px" }} placeholder="请输入密码" />
            </Form.Item>
          </Form>
        </Tabs.Tab>
      </Tabs>

      <div className={style.mesRadio}>
        <Checkbox
          className={style.radio}
          checked={agreed}
          onChange={setAgreed}
        />
        <p>
          已阅读并同意 <span>《妙手医生服务协议》</span>和
          <span>《妙手医生隐私政策》、 《妙手医生儿童个人信息保护规则》</span>
        </p>
      </div>
    </div>
  );
}

export default Index;
